package net.zjitc.tree;

public class Demo {
    public static void main(String[] args) {
        int[] arr = {1,2,3,4,6,7,8,9};
        int key = 5;
        int result = search(arr,key);
        System.out.println(result);
    }

    /**
     * 二分查找:
     * @param arr
     * @param key
     * @return
     */
    private static int search(int[] arr, int key) {
         int left,right,mid;
         left = 0;
         right = arr.length-1;


         while (right>=left){

             mid = (left+right)/2;

             if (arr[mid] > key){
                 right = mid-1;

             }else if (arr[mid] < key){
                 left = mid+1;

             }else {
                 return arr[mid];
             }
         }
         return -1;
    }
}
